package org.yanex.apitest;

import java.util.List;

import org.yanex.project.api.API;
import org.yanex.project.api.APIFactory;
import org.yanex.project.api.APIFactory.Protocol;
import org.yanex.project.api.APIFactory.UnsupportedProtocolException;
import org.yanex.project.api.items.Category;
import org.yanex.project.api.items.SelfItemAdapter;
import org.yanex.util.ThreadHelper;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

public class APITestActivity extends Activity {
	
	ListView list;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        API _api;
		try {
			//local network instance
			_api = APIFactory.getInstance().createAPI(
					"http://192.168.1.14/api/", Protocol.XML);
		} catch (UnsupportedProtocolException e) {
			System.err.println("Failed to create API object.");
			System.exit(0);
			return;
		}
		
		final API api = _api;
        
        list = (ListView)findViewById(R.id.list);
        
        final ProgressDialog dialog = new ProgressDialog(this);
        dialog.setTitle(R.string.loading);
        dialog.show();
        
        new ThreadHelper() {
			
        	List<Category> categories;
        	
        	@Override
        	public void error() {
        		dialog.dismiss();
        		Toast.makeText(APITestActivity.this, 
        				getString(R.string.error_while_loading),
        				Toast.LENGTH_SHORT).show();
        	}
        	
			@Override
			public boolean task() {
				try {
					categories = api.getCategories(0);
					return true;
				} catch (Exception e) {
					e.printStackTrace();
					return false;
				}
			}
			
			@Override
			public void finalizator() {
				dialog.dismiss();
				
				SelfItemAdapter adapter = new SelfItemAdapter(
						APITestActivity.this, categories);
				
				list.setAdapter(adapter);
			}
		}.start();
    }
}